﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseExtendsions
{

    /// <summary>
    /// 自定义的转换器，把 long 类型序列化为字符串
    /// </summary>
    public class LongToStringConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(long) || objectType == typeof(long?);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;

            if (reader.Value == null)
            {
                if (IsNullableType(objectType))
                {
                    return null;
                }
                else return 0;

            }
            if (string.IsNullOrWhiteSpace(reader.Value.ToString()))
            {
                if (IsNullableType(objectType)) return null;
                else return 0;
            }
            if (long.TryParse(reader.Value.ToString(), out long l))
                return l;
            else
                throw new Exception($"{reader.Path} Cannot convert to long.");
        }
        public bool IsNullableType(Type that)
        {
            return !(that == null) && !that.IsArray && that.FullName.StartsWith("System.Nullable`1[");
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
                writer.WriteNull();
            else
                writer.WriteValue(value.ToString());
        }
    }
}
